<template>
    <div>
        <div class="panel-subs-body-box-hd">
            <div class="hd">
                <span :title="pItem.moduleName + ' - 明细'" class="body-box-hd-span">{{ pItem.moduleName + ' - 明细' }}</span>
            </div>
            <div class="panel-subs-body-box-icon">
                <el-button size="mini" type="primary" @click="searchModule" v-loading="btnLoading">查询</el-button>
                <el-button size="mini" type="primary" @click="loadout" v-loading="btnLoading">导出</el-button>
                <div v-show="!isFullScreen" title="放大" class="zc-icon img-dachuang" @click="onFullScreen"></div>
                <div v-show="isFullScreen" title="缩小" class="zc-icon img-xiaochuang" @click="onFullScreen"></div>
                <div class="zc-icon img-guanbi" title="关闭" @click="onCloseTable"></div>
            </div>
        </div>
        <div class="panel-subs-body-box-main">
            <el-table
                v-table-top="detailSearchParam.paging.currentPage"
                :data="detailData"
                :row-style="{ height: '40px' }"
                :height="isFullScreen === pItem.moduleCode ? 'calc(100vh - 110px)' : 'calc(50vh - 155px)'"
                @cell-click="cellClick"
                size="mini"
                row-key="resultId"
                border
                v-loading="isFullScreen === null ? detailLoading : detailLoading && isFullScreen === pItem.moduleCode"
                :default-sort="{ prop: sortPropDetail, order: sortOrderDetail }"
                @sort-change="changeTableSortDetail"
            >
                <!-- :id="isFullScreen === null ? '' : 'table'" -->
                <el-table-column
                    v-for="(col, index) in columns"
                    :key="col.val + col.name + index"
                    :prop="col.val"
                    :label="col.name"
                    :width="col.width"
                    :show-overflow-tooltip="col.showOverflowTooltip"
                    :sortable="col.sortable"
                    :min-width="col.minWidth"
                    id="column"
                >
                    <template slot-scope="scope">
                        <span v-if="col.val === 'thresholdValue'">
                            {{ formatThresholdValue(scope.row) }}
                        </span>
                        <span v-else-if="col.val === 'thresholdType'">
                            <StatusTag :code="scope.row.thresholdType"></StatusTag>
                        </span>
                        <span v-else-if="col.val === 'calculateValue'">
                            <span
                                v-if="scope.row.calculateValue != null"
                                :style="{
                                    textDecoration: 'underline',
                                    textDecorationColor: ThresholadEntryColor[scope.row.thresholdType],
                                    color: ThresholadEntryColor[scope.row.thresholdType],
                                    cursor: 'pointer',
                                }"
                                slot="reference"
                                @click="openEntryResultDetail(scope.row)"
                            >
                                {{ formatCalculateValue(scope.row) || '--' }}
                            </span>
                            <span v-else>--</span>
                        </span>
                        <span v-else-if="col.val === 'stockCodes'">
                            <el-tag size="small" style="" v-if="scope.row.stockInfos != null && scope.row.stockInfos.length > 1" slot="reference">
                                <el-tooltip placement="top">
                                    <ul slot="content" style="height: fit-content; max-height: 200px; overflow: auto">
                                        <li :key="item.dictKey" v-for="item in scope.row.stockInfos">
                                            {{ item.dictKey ? item.dictKey + ':' + item.dictKeyName : item.dictCode }}
                                        </li>
                                    </ul>
                                    <span>{{ scope.row.stockInfos.length + '个证券' }}</span>
                                </el-tooltip>
                            </el-tag>
                            <span v-else-if="scope.row.stockInfos != null && scope.row.stockInfos.length == 1">
                                {{
                                    scope.row.stockInfos[0].dictKey
                                        ? scope.row.stockInfos[0].dictKey + ':' + scope.row.stockInfos[0].dictKeyName
                                        : scope.row.stockInfos[0].dictCode
                                }}
                            </span>
                            <span v-else> --</span>
                        </span>

                        <span v-else-if="col.val === 'comment'">
                            <el-input
                                v-if="editShow && scope.$index == editRow.index && scope.row == editRow"
                                v-model="scope.row.comment"
                                size="small"
                                @focus="focus(scope.row)"
                                @blur="blur(scope.row)"
                                ref="commentInput"
                            ></el-input>
                            <span v-else>
                                {{ scope.row.comment }}
                            </span>
                        </span>

                        <span v-else-if="col.val === 'userInfos'">
                            {{ handleUserFormatter(scope.row) }}
                        </span>
                        <span v-else>{{ scope.row[col.val] || '--' }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-content">
                <risk-pagination :paging="detailSearchParam.paging" @page-change="currentDetailChange"></risk-pagination>
            </div>
        </div>
        <!-- 明细查询页面 -->
        <yh-dialog :visible.sync="searchModuleDetailVisible" title="模块明细数据查询" drag :close-on-click-modal="false" width="600px" append-to-body>
            <el-form label-width="100px" size="mini" ref="detailSearchRef" :model="detailSearchParam">
                <el-form-item label="条目编号" prop="accurateSelect">
                    <el-input v-model="entryCodes" placeholder="支持','分割" size="mini" style="width: calc(100% - 100px)"></el-input>
                    <el-checkbox
                        v-model="detailSearchParam.accurateSelect"
                        size="mini"
                        style="width: 87px; border: 1px solid #e5e5ea; height: 26px; line-height: 22px; padding: 2px; margin-left: 8px"
                        >准确搜索</el-checkbox
                    >
                </el-form-item>
                <el-form-item label="条目组" prop="entryGroups">
                    <el-select v-model="detailSearchParam.entryGroups" style="width: 100%" clearable collapse-tags filterable multiple>
                        <el-option
                            v-for="item in entryGroupsDict"
                            :key="item.groupCode"
                            :value="item.groupCode"
                            :label="item.groupCode + ' ' + item.groupName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="风险说明" prop="entryName">
                    <el-input v-model="detailSearchParam.entryName" style="width: 100%"></el-input>
                </el-form-item>
                <el-form-item label="触警类型" prop="thresholdTypes">
                    <el-select v-model="detailSearchParam.thresholdTypes" style="width: 42%" clearable collapse-tags filterable multiple>
                        <el-option v-for="item in ThresholdTypeDict" :key="item.dictKey" :value="item.dictKey" :label="item.dictKeyName"> </el-option>
                    </el-select>
                    <!--
                    <span> 处理状态 </span>
                    <el-select v-model="detailSearchParam.handleStatuses" style="width: 43%" clearable collapse-tags filterable multiple>
                        <el-option v-for="(value, key) in handleStatusAll" :key="key" :value="key" :label="value"> </el-option>
                    </el-select>
                    -->
                </el-form-item>
                <el-form-item label="产品代码" prop="selectedFundCodes">
                    <!-- <el-select v-model="detailSearchParam.selectedFundCodes" style="width: 100%" clearable filterable multiple collapse-tags>
                        <el-option v-for="item in fundInfo" :key="item.dictKey" :value="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName">
                        </el-option>
                    </el-select> -->
                    <el-select
                        v-model="detailSearchParam.selectedFundCodes"
                        :filter-method="getFundInfoList"
                        :loading="stockReportState"
                        style="width: 100%"
                        clearable
                        filterable
                        multiple
                        collapse-tags
                        placeholder="请选择"
                    >
                        <el-option v-for="item in fundInfo" :key="item.dictKey" :value="item.dictKey" :label="item.dictKey + ' ' + item.dictKeyName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证券代码" prop="stockCodes">
                    <el-select
                        v-model="detailSearchParam.stockCodes"
                        filterable
                        multiple
                        collapse-tags
                        clearable
                        remote
                        :remote-method="getStockCodeList"
                        :loading="selectLoading"
                        placeholder="请输入代码或名称"
                        size="mini"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in stockCodeSelectData"
                            :key="item.dictKey"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                            :value="item.dictKey"
                        >
                        </el-option>
                    </el-select> </el-form-item
                ><el-form-item label="备注信息" prop="comment">
                    <el-input v-model="detailSearchParam.comment" style="width: 100%"> </el-input>
                </el-form-item>
                <el-form-item label="处理人" prop="handleUsers">
                    <el-select v-model="detailSearchParam.handleUsers" style="width: 100%" collapse-tags multiple clearable filterable>
                        <el-option
                            v-for="item in handleUsers"
                            :key="item.dictKey"
                            :value="item.dictCode"
                            :label="item.dictKey + ' ' + item.dictKeyName"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="resetSearchModule"> 重 置 </el-button>
                <el-button size="mini" @click="cancelSearchModule"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="submitSearchModule"> 确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import DictionConstUtil from '@/utils/diction-const-util';
import { downLoadFile } from '@/utils/request';
import { checkPermission, numberFormat, timeFormat, numberFormatXDAY, getConfigItem, numberFormatCIB, unitShow } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { localeData } from 'moment';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import RiskPagination from '@/common/components/risk-pagination.vue';
@Component({
    name: 'TriggerDetail',
    components: {
        StatusTag,
        RiskPagination,
    },
})
export default class TriggerDetail extends Vue {
    @Prop() pItem;
    @Prop() entryGroupsDict;
    @Prop() handleUsers;
    @Prop() searchParam;
    @Prop() isFullScreen;
    // @Prop() fundInfo;
    @Prop() reload;
    @Prop() hasChangeObj;
    @Prop() detailDynamicColumn;
    @Prop() operateType;

    private fundInfo = []; // 基金名称列表
    stockReportState: boolean = false;
    timer: any = null;

    @Watch('hasChangeObj', { deep: true })
    async hasChangeObjHandle(oldVal, newVal) {
        if (this.pItem.moduleCode == this.hasChangeObj.moduleCode) {
            // console.log(oldVal, newVal);

            // console.log('hasChangeObj');
            // console.log(this.hasChangeObj, 'detail' + this.pItem.index);
            this.handleSearchParam();
            // 测试代码1
            if (this.operateType !== this.hasChangeObj.operateType) {
                console.error(this.operateType, 'hasChangeObjHandle--------this.operateType');
            } else {
                // console.log(this.operateType, 'hasChangeObjHandle--------operateType为autoRefresh');
            }

            this.detailData = await this.getDetail(this.hasChangeObj.operateType);
        }
    }

    // 处理查询字段
    handleSearchParam() {
        this.detailSearchParam = { ...this.detailSearchParam, ...this.hasChangeObj.moduleSearchParam };
        // console.log(this.detailSearchParam, 'detailSearchParam');
        let values = this.hasChangeObj.selectionValues;
        let keys = [];
        if (values && values.length > 0) {
            keys = values.map(item => item.entryCode).filter(item => this.hasChangeObj.tableKeys.includes(item));
        }
        // let codes = this.hasChangeObj.moduleSearchParam.entryCodes;
        this.detailSearchParam.entryCodes = keys;
        this.entryCodes = keys.toString();
    }

    @Watch('detailDynamicColumn', { immediate: true, deep: true })
    onWatchDetailColumn() {
        if (this.detailDynamicColumn && this.detailDynamicColumn.length > 0) {
            this.columns = this.detailDynamicColumn;
        }
    }

    // @Watch('reload', { deep: true })
    // reloadData() {
    //     this.submitSearchModule();
    // }
    isFirst: boolean = true;
    tempPsize: number = 10;
    @Watch('isFullScreen')
    handleFull() {
        // if (this.isFirst) {
        //     // this.$nextTick(() => {
        //     let height = document.body.clientHeight - 160;
        //     this.pSize = Math.floor(height / 40);
        //     this.isFirst = false;
        //     // });
        // }
        // if (this.isFullScreen && !this.isFirst) {
        //     this.detailData.length > 0 && this.handlePSize();
        // }
        if (this.isFullScreen && this.isFullScreen == this.pItem.moduleCode) {
            console.log('页面大小变化');

            let height = document.body.clientHeight - 160;
            this.pSize = Math.floor(height / 40);
        }

        // this.handlePSize();
    }

    pSize: number = 10;
    @Watch('pSize')
    async handlePSize() {
        if (this.isFullScreen && this.isFullScreen == this.pItem.moduleCode) {
            this.detailSearchParam.paging.pageSize = this.pSize;

            // this.detailData.length > 0 &&
            await this.handleSizeChange(this.pSize);
        }
    }

    async mounted() {
        window.onresize = async () => {
            // console.log(document.body.clientHeight - 160);
            let height = document.body.clientHeight - 160;
            this.pSize = Math.floor(height / 40);
            console.log(this.pSize);
        };

        this.getFundInfoList('');
        this.handleSearchParam();
    }

    Math = Math;
    timeFormat = timeFormat;
    numberFormat = numberFormat;
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    // 颜色字典
    private ThresholadEntryColor = {
        '0': '#222',
        '1': '#222',
        '2': '#222',
        '3': '#d9001b',
        '4': '#222',
    };

    // 状态
    private handleStatusAll = {
        '1': '待处理',
        '2': '已处理',
        '3': '无需处理',
    };

    // ThresholdTypeSelection: any[] = [];
    private ThresholdTypeDict = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey != '4');
    // 符号字典
    private CompareDirection = {
        '0': '>',
        '1': '<',
        '2': '>=',
        '3': '<=',
        '4': '=',
        '5': '<>',
        '6': ' ',
    };

    TimeSendMessage: any = null;
    // key: number = -1;
    private columns: any[] = [];

    private detailData: any = []; // 模板明细表格数据

    private searchModuleDetailVisible: boolean = false; // 模板搜索页面

    private entryCodes: string = ''; // 模板条目编号显示值

    detailLoading: boolean = false;

    private sortPropDetail: string = ''; // 排序字段

    private sortOrderDetail: string = ''; // 排序方式

    private selectLoading: boolean = false; // 下拉框加载

    private stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    btnLoading: boolean = false;

    pageSizes: any[] = [5, 10, 15, 20];

    // 明细
    private detailSearchParam = {
        accurateSelect: true,
        comment: '',
        entryCodes: [],
        entryName: '',
        selectedFundCodes: [],
        fundCodes: [],
        fundGrCodes: [],
        handleStatuses: [],
        handleUsers: [],
        moduleCode: '',
        stockCodes: [],
        thresholdTypes: ['3'],
        useEntryPanelCode: '',
        paging: {
            currentPage: 1,
            pageSize: 10,
            total: 0,
        },
        sort: '',
    };

    // 获取证券代码下拉框数据
    private getStockCodeList(e: string): void {
        this.selectLoading = true;
        this.$axios
            .post('/dict/stock/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    // 查询
    searchModule(): void {
        this.searchModuleDetailVisible = true;
    }

    // 确认模块查询
    async submitSearchModule() {
        this.cancelSearchModule();
        this.detailSearchParam.entryCodes = this.entryCodes ? this.entryCodes.split(',') : [];
        this.detailSearchParam.paging.currentPage = 1;
        this.detailData = await this.getDetail();
    }

    // 取消模块查询
    cancelSearchModule() {
        this.searchModuleDetailVisible = false;
    }

    // 重置模块查询
    resetSearchModule() {
        this.entryCodes = '';
        (this.$refs.detailSearchRef as any).resetFields();
        this.detailSearchParam.handleStatuses = [];
    }

    // 导出
    loadout() {
        // this.btnLoading = true;
        downLoadFile({
            url: '/panorama/module/result/detail/export',
            method: 'post',
            data: this.detailSearchParam,
        });
        // .then((res: any) => {
        //     this.yh_message_success('导出成功');
        //     this.btnLoading = false;
        // })
        // .catch(() => {
        //     this.yh_message_error('导出失败');
        //     this.btnLoading = false;
        // });
    }

    // 明细分页
    async currentDetailChange(value) {
        //   this.detailSearchParam.paging.currentPage = value;
        this.detailData = await this.getDetail();
    }

    // 切换页码
    async handleSizeChange(value) {
        this.detailSearchParam.paging.currentPage = 1;
        this.detailSearchParam.paging.pageSize = value;

        const isClu = this.pageSizes.includes(value);
        this.pageSizes = isClu ? this.pageSizes : [5, 10, 15, 20].concat([value]).sort((a, b) => a - b);

        this.detailData = await this.getDetail();
        // this.key++;
    }

    // 首页/尾页
    async toPage(type, moduleCode) {
        let page = 1;
        if (type == 'last') {
            page = Math.ceil(this.detailSearchParam.paging.total / this.detailSearchParam.paging.pageSize);
        }
        this.currentDetailChange(page);
    }

    // 获取明细
    private getDetail(operateType?: string) {
        // console.log('获取明细');
        this.detailLoading = true;
        this.detailSearchParam.moduleCode = this.pItem.moduleCode;
        // this.detailSearchParam.useEntryPanelCode = this.searchParam.useEntryPanelCode;
        // this.detailSearchParam.fundCodes = this.searchParam.fundCodes;
        // this.detailSearchParam.fundGrCodes = this.searchParam.fundGrCode;

        // this.TimeSendMessage && clearInterval(this.TimeSendMessage);
        // this.setT();

        return new Promise((resolve, reject) => {
            // this.$axios
            //     .post('/panorama/module/result/detail', this.detailSearchParam)
            this.$axios({
                url: '/panorama/module/result/detail',
                method: 'post',
                data: this.detailSearchParam,
                headers: { operateType: operateType },
            })
                // .post('/panorama/module/result/detail', this.detailSearchParam)
                .then((res: any) => {
                    res.list &&
                        res.list.forEach((item, index) => {
                            this.$set(item, 'index', index);
                        });
                    this.detailSearchParam.paging.total = res.total;
                    this.detailLoading = false;
                    resolve(res.list);
                })
                .catch(err => {
                    this.detailSearchParam.paging.total = 0;
                    this.detailLoading = false;
                    reject(err);
                });
        });
    }

    // 全屏功能
    onFullScreen() {
        this.$emit('onFullScreen', this.pItem.moduleCode);
    }

    // 关闭表格
    onCloseTable() {
        this.$emit('onCloseTable', this.pItem.moduleCode);
    }

    // 明细排序
    detailSortObject = {
        resultId: 'N_RESULT_ID',
        entryCode: 'C_ENTRY_CODE',
        entryName: 'c_entry_name',
        compareType: 'C_COMPARE_TYPE',
        thresholdValue: 'N_THRESHOLD_VALUE',
        fundCode: 'c_fund_code',
        // fundNameSt: 'C_FUND_NAME_ST',
        fundNameSt: 'c_fund_code',
        calculateValue: 'N_CALCULATE_VALUE',
        comment: 'C_COMMENT',
        handleStatus: 'C_HANDLE_STATUS',
        stockCodes: 'length(C_STOCK_CODES)',
        // handleUser: 'C_HANDLE_USER',
        userInfos: 'C_HANDLE_USER',
        calLogic: 'C_CAL_LOGIC',
        originalAccoutId: 'N_OR_AC_ID',
        thresholdType: 'C_THRESHOLD_TYPE',
        issueInfoName: 'C_ISSUE_NAME_ST',
    };

    // 排序改变
    private async changeTableSortDetail(column) {
        this.sortPropDetail = column.prop;
        this.sortOrderDetail = column.order;
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        this.detailSearchParam.sort = this.detailSortObject[column.prop] + ' ' + sortType;
        this.detailData = await this.getDetail();
    }

    // 处理人
    handleUserFormatter(row) {
        let users = row.userInfos;
        let value = XEUtils.map(users, item => item.dictKeyName);
        return users && users.length ? value.toString() : '--';
    }

    editShow: boolean = false;
    editRow: any = {};
    cellClick(row, column) {
        this.editRow = row;

        if (column.property == 'comment') {
            this.editShow = true;
        }
        // (this.$refs.commentInput as any).focus();
    }

    oldComment: string = '';
    oldIndex: number = -1;

    // 失去焦点
    blur(row: any) {
        this.editShow = false;
        if (row.comment != this.oldComment && row.index == this.oldIndex) {
            // 调用方法
            let users = row.handleUser ? row.handleUser.split(',') : [];
            let userCode = getUser().userCode;
            let value = users.find(item => item == userCode);
            if (!value) {
                users.push(userCode);
            }
            row.handleUser = users.toString();

            this.$axios
                .post('/panorama/module/result/edit', {
                    handleUser: users.toString(),
                    comment: row.comment,
                    resultId: row.resultId,
                    handleStatus: row.handleStatus,
                })
                .then(async (res: any) => {
                    this.yh_message_success('编辑成功');

                    this.submitSearchModule();
                    // 备注成功了，重新查询表格
                    this.$emit('edit', this.pItem.moduleCode);
                });
        }
    }

    // 获得焦点
    focus(row) {
        this.oldComment = row.comment;
        this.oldIndex = row.index;
        // console.log(this.oldComment, this.oldIndex);
    }

    // 实际值明细
    openEntryResultDetail(row) {
        if (!checkPermission('B_0342')) {
            console.log('onClick: 该账号无明细数据查看权限!');
            return;
        }
        this.$emit('openEntryResultDetail', { row: row, pItem: this.pItem, type: 'detail' });
    }

    fomatterParam(row, column, cellValue) {
        return cellValue || '--';
    }

    getFundInfoList(val) {
        this.stockReportState = true;
        try {
            clearTimeout(this.timer);
        } catch (e) {}
        this.timer = setTimeout(() => {
            this.$axios
                .get('/fundInfo/list/byUser/like?fundCodeOrName=' + encodeURIComponent(val))
                .then((res: any) => {
                    this.fundInfo = res.map(item => {
                        return { dictKey: item.fundCode, dictKeyName: item.fundNameSt };
                    });
                    this.stockReportState = false;
                })
                .catch(() => {
                    this.stockReportState = false;
                });
        }, 300);
    }

    formatThresholdValue(row): string {
        if (row.thresholdValue || row.thresholdValue == 0) {
            return this.CompareDirection[row.compareType] + numberFormatCIB(row.thresholdValue, row.unit, 'thresholdValue') + unitShow(row.unit);
        }
        return '--';
    }

    formatCalculateValue(row) {
        if (row.calculateValue || row.calculateValue == 0) {
            return numberFormatCIB(row.calculateValue, row.unit) + unitShow(row.unit);
        }
        return '--';
    }
}
</script>
<style lang="scss" scoped>
.panel-subs-body-box-main {
    .pagination-content {
        float: right;
        line-height: 28px;

        .toPageS {
            border: 1px solid #e5e5ea;
            border-radius: 3px;
        }
        .first {
            margin-right: 10px;
        }
        .last {
            margin-left: 10px;
        }

        /deep/ .el-pagination {
            padding: 5px 5px 5px 0 !important;
            display: inline-block;
            .el-select .el-input .el-input__inner {
                background: transparent;
                border: 1px solid #e5e5ea;
            }
        }
    }
}

/deep/ .el-table__body-wrapper {
    min-height: calc(100% - 48px) !important;
}
</style>
